package com.szrt.mysql.demo14.transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


/**
 * Unit test for simple App.
 */
public class TransactionTest {
	Connection conn=null;
	PreparedStatement ps=null;
	
	@SuppressWarnings("unused")
	@org.junit.Test
	public void test(){
		 try {
			 Class.forName("com.mysql.jdbc.Driver");
			 conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zsrt1612","root","123456");
			 conn.setAutoCommit(false);//设置事务手工提交
			
			 ps=conn.prepareStatement("update account set money=money-100 where id=1");
			 ps.executeUpdate();
			 int i=1/0;
			 ps=conn.prepareStatement("update account set money=money+100 where id=2");
			 ps.executeUpdate();
		 } catch (Exception e) {
			e.printStackTrace();
			try {
				//如果有异常 全部回滚
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			
		}finally {
			try {
				//最终不管有没有异常 都需要提交 释放资源
				conn.commit();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
   
}
